﻿using System;
using System.IO;
using System.Text;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI.Docking;
using WeifenLuo.WinFormsUI.Base;
using CustomDataGridView;

namespace HRM
{
    public partial class FormPersonalProfile : FormBaseDataMstDtl
    {

        #region Declare Variables
        private string msOpenDialogFileName = String.Empty;
        private Ctrl_General mCtrlGeneral;

        private DataSet mdsPersonalGeneral;
        private SqlDataAdapter mdaPFGUpdate;

        //TabPage Professonal Qualification
        private DataSet mdsProfessQualify;
        private SqlDataAdapter mdaPQUpdate;
        CurrencyManager mCurrencyManagerPQ;

        //TabPage Education
        private DataSet mdsEducation;
        private SqlDataAdapter mdaEducationUpdate;
        CurrencyManager mCurrencyManagerEducation;

        //TabPage Health
        private DataSet mdsHealthBas;
        private SqlDataAdapter mdaHealthBasUpdate;
        CurrencyManager mCurrencyManagerHealthBas;

        //TabPage Relative
        private DataSet mdsRelative;
        private SqlDataAdapter mdaRelativeUpdate;
        CurrencyManager mCurrencyManagerRelative;

        //TabPage Contract
        private DataSet mdsContract;
        private SqlDataAdapter mdaContractUpdate;
        CurrencyManager mCurrencyManagerContract;

        //TabPage Working Experience
        private DataSet mdsWrkExperience;
        private SqlDataAdapter mdaWrkExperienceUpdate;
        CurrencyManager mCurrencyManagerWrkExperience;

        //TabPage Internal Transfer
        private DataSet mdsIntTransfer;
        private SqlDataAdapter mdaIntTransferUpdate;
        CurrencyManager mCurrencyManagerIntTransfer;

        //TabPage Foreign Language/ Computing
        private DataSet mdsFLanComputing;
        private SqlDataAdapter mdaFLanComputingUpdate;
        CurrencyManager mCurrencyManagerFLanComputing;
        #endregion

        public FormPersonalProfile()
        {
            InitializeComponent();
            CreateTextBoxButton(txtIDPosition);
            CreateTextBoxButton(txtIDDept);
            CreateTextBoxButton(txtIDResideState);
            CreateTextBoxButton(txtIDResideCountry);
            CreateTextBoxButton(txtIDContState);
            CreateTextBoxButton(txtIDContCountry);
            CreateTextBoxButton(txtIDNative);
            CreateTextBoxButton(txtIDNationality);
            CreateTextBoxButton(txtIDRace);
            CreateTextBoxButton(txtIDLiteracy);
            CreateTextBoxButton(txtIDGLAccGroup);
            CreateTextBoxButton(txtIDBank);
        }

        #region override BaseForm load
        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }
        #endregion

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void mdbg_DGV_MouseDown(object sender, MouseEventArgs e)
        {
            base.mdbg_DGV_MouseDown(sender, e);
        }

        #region Override Load Master Data
        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Personal Profile data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        #endregion

        #region LoadData method
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ClearDataBinding(this);
                if (mRowManager != null)
                {
                    mRowManager.SuspendBinding();
                    mRowManager.PositionChanged -= new EventHandler(RowMaster_Changed);
                }
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_SQL = "Select PF.ID_Emp, PF.Emp_FirstName, PF.Emp_MiddleName, PF.Emp_LastName, PF.Emp_NameVN, PF.Emp_NameEN, PF.Emp_Alias, PF.Att_Code, "
                    + "PF.JobTitle, PF.ID_Position, POS.Position_Name, PF.ID_Dept, DEP.Dept_Name, "
                    + "PF.Office_Phone, PF.Hand_Phone, PF.Home_Phone, PF.E_Mail, PF.Active, PF.Emp_Picture, "
                    + "PF.Reside_StreetNo, PF.Reside_StreetName, PF.Reside_Block, PF.Reside_BuildFloorRoom, PF.Reside_ZipCode, PF.Reside_City, PF.Reside_HomeTown, "

                    + "PF.Reside_ID_State, RS.Name_Country as ResideState_Name, PF.Reside_ID_Country, RC.Name_Country as ResideCountry_Name, PF.Reside_Address, "
                    + "PF.Contact_StreetNo, PF.Contact_StreetName, PF.Contact_Block, PF.Contact_BuildFloorRoom, PF.Contact_ZipCode, PF.Contact_City, PF.Contact_HomeTown, "

                    + "PF.Contact_ID_State, CS.Name_Country as ContactState_Name, PF.Contact_ID_Country, CC.Name_Country as ContactCountryName, PF.Contact_Address, "
                    + "PF.Entry_Date, PF.Resign_Date, PF.Resign_Reason, PF.ID_Native, NATIVE.Name_Country as Native_Name, PF.ID_Race, RACE.Race_Name, PF.Religion, "
                    + "PF.ID_Country, COUNTRY.Name_Country, PF.ID_Literacy, LIT.Literacy_Name, PF.Note, "
                    + "PF.Gender, PF.DOB, PF.POB, PF.CardNo_ID, PF.DateOfIssue, PF.PlaceOfIssue, PF.PassportExpirDate, PF.Foreigner, "
                    + "PF.Basic_Salary, PF.CompAllowance, PF.ID_AccGroup, GLA.GLAccGroup_Name, PF.ID_Bank, BANK.Bank_Name, PF.Bank_Account, PF.CIF, PF.FollowTimeAtt, PF.Wrk_Days, PF.EmpType, "
                    + "PF.Insurance, PF.TradeUnion, PF.Probation, "
                    + "PF.CreatedUser, PF.UpdatedUser, PF.CreatedDate, PF.UpdatedDate "

                    + " From HRM_PersonalProfile PF"
                    + " left outer join HRM_Position POS on PF.ID_Position = POS.ID_Position"
                    + " left outer join HRM_Department DEP on PF.ID_Dept = DEP.ID_Dept"

                    + " left outer join HRM_Country RS on PF.Reside_ID_State = RS.ID_Country and RS.CType = 'A' " // State
                    + " left outer join HRM_Country RC on PF.Reside_ID_Country = RC.ID_Country and RC.CType = 'C' " // country
                    + " left outer join HRM_Country CS on PF.Contact_ID_State = CS.ID_Country and CS.CType = 'A' "
                    + " left outer join HRM_Country CC on PF.Contact_ID_Country = CC.ID_Country and CC.CType = 'C' "

                    + " left outer join HRM_Country NATIVE on PF.ID_Native = NATIVE.ID_Country and NATIVE.CType = 'A' "
                    + " left outer join HRM_Race RACE on PF.ID_Race = RACE.ID_Race"
                    + " left outer join HRM_Country COUNTRY on PF.ID_Country = COUNTRY.ID_Country and COUNTRY.CType = 'C' "
                    + " left outer join HRM_Literacy LIT on PF.ID_Literacy = LIT.ID_Literacy"
                    + " left outer join HRM_GLAccGroup_Header GLA on PF.ID_AccGroup = GLA.ID_GLAccGroup"
                    + " left outer join HRM_Bank BANK on PF.ID_Bank = BANK.ID_Bank"

                    + " Order By PF.ID_Emp ";

                mdsPersonalGeneral = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonalProfile");
                mCtrlGeneral.GetAllData(out mdaPFGUpdate, "HRM_PersonalProfile", " Order By ID_Emp ");
                if (mdsPersonalGeneral == null) return;

                //Binding tPageGeneral : TextBox, Label
                txtIDEmp.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Emp"));
                txtFirstName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Emp_FirstName"));
                txtMiddleName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Emp_MiddleName"));
                txtLastName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Emp_LastName"));
                txtFullName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Emp_NameVN"));
                txtJobTitle.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "JobTitle"));
                txtIDPosition.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Position"));
                lblPositionName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Position_Name"));
                txtIDDept.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Dept"));
                lblDeptName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Dept_Name"));
                txtAttCode.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Att_Code"));
                txtEngName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Emp_NameEN"));
                txtNickName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Emp_Alias"));
                txtOffPhone.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Office_Phone"));
                txtHomePhone.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Home_Phone"));
                txtMobilePhone.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Hand_Phone"));
                txtEmail.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "E_Mail"));
                
                // tab Address
                txtResideStreet.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_StreetName"));
                txtResideStreetNo.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_StreetNo"));
                txtResideBlock.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_Block"));
                txtResideBuilding.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_BuildFloorRoom"));
                txtResideZipCode.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_ZipCode"));
                txtResideCity.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_City"));
                txtResideHomeTown.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_HomeTown"));
                txtIDResideState.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_ID_State"));
                lblResideStateName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ResideState_Name"));
                txtIDResideCountry.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Reside_ID_Country"));
                lblResideCountryName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ResideCountry_Name"));

                txtContStreet.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_StreetName"));
                txtContStreetNo.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_StreetNo"));
                txtContBlock.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_Block"));
                txtContBuilding.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_BuildFloorRoom"));
                txtContZipCode.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_ZipCode"));
                txtContCity.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_City"));
                txtContHomeTown.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_HomeTown"));
                txtIDContState.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_ID_State"));
                lblContStateName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ContactState_Name"));
                txtIDContCountry.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Contact_ID_Country"));
                lblContCountryName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ContactCountryName"));
                // tab Administration
                dtpStartDate.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Entry_Date"));
                dtpResignDate.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Resign_Date"));
                txtResignReason.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Resign_Reason"));
                txtIDNative.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Native"));
                lblNativeName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Native_Name"));
                txtIDNationality.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Country"));
                lblNationalityName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Name_Country"));
                txtIDRace.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Race"));
                lblRaceName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Race_Name"));
                txtReligion.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Religion"));
                txtIDLiteracy.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Literacy"));
                lblLiteracyName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Literacy_Name"));
                txtNote.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Note"));

                // tab Personal
                dtpDOB.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "DOB"));
                txtPOB.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "POB"));
                txtIDCardPassport.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "CardNo_ID"));
                dtpIssueDate.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "DateOfIssue"));
                txtPOI.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "PlaceOfIssue"));
                dtpExpirDate.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "PassportExpirDate"));
                //chkForeigner.DataBindings.Add(new Binding("Checked", mdsPersonalGeneral.Tables[0], "Foreigner"));
                //tab Finance
                //nudBasicSal.DataBindings.Add(new Binding("Value", mdsPersonalGeneral.Tables[0], "Basic_Salary"));
                //nudAllowance.DataBindings.Add(new Binding("Value", mdsPersonalGeneral.Tables[0], "CompAllowance"));
                txtIDGLAccGroup.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_AccGroup"));
                lblGLAccGrpName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "GLAccGroup_Name"));
                txtBankAccount.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Bank_Account"));
                txtBankCIF.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "CIF"));
                txtIDBank.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "ID_Bank"));
                lblBankName.DataBindings.Add(new Binding("Text", mdsPersonalGeneral.Tables[0], "Bank_Name"));
 
                mRowManager = (CurrencyManager)txtIDEmp.BindingContext[mdsPersonalGeneral.Tables[0]];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                SetData2List(mdsPersonalGeneral);
                if (mRowManager.Position >= 0) PGSetValue();
                SetReadOnly(this, false);
                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Personal Profile data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region PGSetValue
        private void PGSetValue()
        {
            DataRow dr = mdsPersonalGeneral.Tables[0].Rows[mRowManager.Position];
            //CheckBox
            chkForeigner.Checked = (dr["Foreigner"] == DBNull.Value ? false : (bool)dr["Foreigner"]);
            chkActEmp.Checked = (dr["Active"] == DBNull.Value ? false : (bool)dr["Active"]);
            chkIns.Checked = (dr["Insurance"] == DBNull.Value ? false : (bool)dr["Insurance"]);
            chkTU.Checked = (dr["TradeUnion"] == DBNull.Value ? false : (bool)dr["TradeUnion"]);
            //Combobox
            cboGender.SelectedIndex = (dr["Gender"] == DBNull.Value ? 0 : (int)dr["Gender"]);
            cboFollowTimeAtt.SelectedIndex = (dr["FollowTimeAtt"] == DBNull.Value ? 0 : (int)dr["FollowTimeAtt"]);
            cboEmpType.SelectedIndex = (dr["EmpType"] == DBNull.Value ? 0 : (int)dr["EmpType"]);
            cboProbation.SelectedIndex = (dr["Probation"] == DBNull.Value ? 0 : (int)dr["Probation"]);

            nudBasicSal.Value = (dr["Basic_Salary"] == DBNull.Value ? 0 : (decimal)dr["Basic_Salary"]);
            nudAllowance.Value = (dr["CompAllowance"] == DBNull.Value ? 0 : (decimal)dr["CompAllowance"]);

            if (dr["Emp_Picture"] != DBNull.Value)
                pbxEmployee.Image = mCtrlGeneral.GetAvatar((Byte[])dr["Emp_Picture"]);
            else pbxEmployee.Image = null;
        }
        #endregion

        #region SetReadOnly
        //Set ReadOnly or Not for : TextBox, RadioButton, CheckBox, DateTimePicker
        private void SetReadOnly(Control aCtrl, bool abReadOnly)
        {
            foreach (Control lCtrl in aCtrl.Controls)
            {
                //MessageBox.Show(lCtrl.GetType().ToString(), lCtrl.Name);
                switch (lCtrl.GetType().ToString())
                {
                    case "System.Windows.Forms.GroupBox":
                        GroupBox lctr_groupBox = (GroupBox)lCtrl;
                        SetReadOnly(lctr_groupBox, abReadOnly);
                        break;

                    case "System.Windows.Forms.TabControl":
                        TabControl lctr_tabControl = (TabControl)lCtrl;
                        SetReadOnly(lctr_tabControl, abReadOnly);
                        break;

                    case "System.Windows.Forms.TabPage":
                        TabPage lctr_tabPage = (TabPage)lCtrl;
                        SetReadOnly(lctr_tabPage, abReadOnly);
                        break;

                    case "System.Windows.Forms.Panel":
                        Panel lctr_panel = (Panel)lCtrl;
                        SetReadOnly(lctr_panel, abReadOnly);
                        break;

                    case "System.Windows.Forms.TextBox":
                        ((TextBox)lCtrl).ReadOnly = !abReadOnly;
                        break;

                    case "System.Windows.Forms.RadioButton":
                        ((RadioButton)lCtrl).AutoCheck = abReadOnly;
                        break;

                    case "System.Windows.Forms.CheckBox":
                        ((CheckBox)lCtrl).AutoCheck = abReadOnly;
                        break;
                    case "System.Windows.Forms.DateTimePicker":
                        ((DateTimePicker)lCtrl).Enabled = abReadOnly;
                        break;

                    case "System.Windows.Forms.ComboBox":
                        ((ComboBox)lCtrl).Enabled = abReadOnly;
                        break;

                    case "System.Windows.Forms.NumericUpDown":
                        ((NumericUpDown)lCtrl).Enabled = abReadOnly;
                        break;
                }
            }
        }
        #endregion

        #region ResetValue
        //Reset: CheckBox, RadioButton,
        //ComboBox, TextBox, NumericUpDown, DateTimePicker
        private void ResetValue(Control aCtrl)
        {
            foreach (Control lCtrl in aCtrl.Controls)
            {
                switch (lCtrl.GetType().ToString())
                {
                    case "System.Windows.Forms.GroupBox":
                        GroupBox lctr_groupBox = (GroupBox)lCtrl;
                        ResetValue(lctr_groupBox);
                        break;

                    case "System.Windows.Forms.TabControl":
                        TabControl lctr_tabControl = (TabControl)lCtrl;
                        ResetValue(lctr_tabControl);
                        break;

                    case "System.Windows.Forms.TabPage":
                        TabPage lctr_tabPage = (TabPage)lCtrl;
                        ResetValue(lctr_tabPage);
                        break;

                    case "System.Windows.Forms.Panel":
                        Panel lctr_panel = (Panel)lCtrl;
                        ResetValue(lctr_panel);
                        break;

                    case "System.Windows.Forms.DateTimePicker":
                        switch (((DateTimePicker)lCtrl).Name)
                        {
                            case "dtpStartDate":
                            case "dtpDOB":
                            case "dtpIssueDate":
                                ((DateTimePicker)lCtrl).Text = "01/01/1990";
                                break;
                            case "dtpResignDate":
                            case "dtpExpirDate":
                                ((DateTimePicker)lCtrl).Text = "31/12/9998";
                                break;
                            default:
                                ((DateTimePicker)lCtrl).Text = DateTime.Now.ToShortDateString();
                                break;
                        } break;

                    case "System.Windows.Forms.ComboBox":
                        if (((ComboBox)lCtrl).Items.Count > 0)
                            ((ComboBox)lCtrl).SelectedIndex = 0;
                        else
                            ((ComboBox)lCtrl).ResetText();
                        break;

                    case "System.Windows.Forms.NumericUpDown":
                        ((NumericUpDown)lCtrl).Value = 0;
                        break;

                    case "System.Windows.Forms.CheckBox":
                        ((CheckBox)lCtrl).Checked = false;
                        break;

                    case "System.Windows.Forms.TextBox":
                        ((TextBox)lCtrl).ResetText();
                        break;
                    case "System.Windows.Forms.PictureBox":
                        ((PictureBox)lCtrl).Image = null;
                        break;
                }
            }
        }
        #endregion

        #region Get Last Position Record
        private int GetLastIDPosition(string asID)
        {
            if (asID.Trim().Equals("") == false)
            {
                int i = 0;
                while (i < mRowManager.Count)
                {
                    DataRow dr = mdsPersonalGeneral.Tables[0].Rows[i++];
                    if (dr["ID_Emp"].ToString().Trim() == asID) return i - 1;
                }
            }
            return -1;
        }
        #endregion

        #region Override add
        public override void add()
        {
            try
            {
                base.add();
                AddTabPage();
                mRowManager.EndCurrentEdit();
                mRowManager.AddNew();
                
                SetReadOnly(this, true);
                //General
                chkActEmp.Checked = true;
                chkForeigner.Checked = false;
                // Administration
                dtpStartDate.Value = DateTime.Now;
                dtpResignDate.Value = dtpResignDate.MaxDate;
                cboFollowTimeAtt.SelectedIndex = 0;
                //Personal
                pbxEmployee.Image = null;
                dtpExpirDate.Value = dtpExpirDate.MaxDate;
                ResetValue(this);
                Application.DoEvents();
                mRowManager.Position = mRowManager.Count - 1;
                //lblstatus.Text = mRowManager.Position.ToString();
               
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot add new. Error: " + ex.Message, ConstantKeys.Title);
            }
        }
        #endregion

        #region Override modify
        public override void modify()
        {
            base.modify();
            SetReadOnly(this, true);
            txtIDEmp.ReadOnly = true;
            //btnIDEmp.Enabled = false;
            //ModifyTabPage();	//Modify TabPage
            tabProfile_SelectedIndexChanged(((TabPage)tab_Profile.SelectedTab), null);
            
        }
        #endregion

        #region Override save
        public override void save()
        {
            mRowManager.EndCurrentEdit();
            
            if (mdsPersonalGeneral == null) return;
            if (txtIDEmp.Text.Trim().Equals(""))
            {
                MessageBox.Show("Cannot update'. Error: Personal Profile. cannot empty.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtIDEmp.Focus();
                return;
            }

            string lsLastID = txtIDEmp.Text.Trim();
            DataRow dr = mdsPersonalGeneral.Tables[0].Rows[mRowManager.Position];
            if (dr.RowState == DataRowState.Modified)
            {
                dr["UpdatedUser"] = mMainForm.ms_UserID;
                dr["UpdatedDate"] = DateTime.Now;
            }
            else if (dr.RowState == DataRowState.Added)
            {
                dr["CreatedUser"] = mMainForm.ms_UserID;
                dr["CreatedDate"] = DateTime.Now;
            }

            if (dr.RowState == DataRowState.Added || dr.RowState == DataRowState.Modified)
            {
                mCtrlGeneral.SetDBNull(dr);
                //General
                dr["Active"] = (chkActEmp.Checked ? true : false);
                dr["Foreigner"] = (chkForeigner.Checked ? true : false);
                // Administration
                dr["Entry_Date"] = dtpStartDate.Value.ToShortDateString();
                dr["Resign_Date"] = dtpResignDate.Value.ToShortDateString();
                dr["FollowTimeAtt"] = cboFollowTimeAtt.SelectedIndex;
                //Personal
                dr["Gender"] = (cboGender.SelectedIndex == -1 ? 0 : cboGender.SelectedIndex);
                dr["EmpType"] = (cboEmpType.SelectedIndex == -1 ? 0 : cboEmpType.SelectedIndex);
                dr["DOB"] = dtpDOB.Value.ToShortDateString();
                dr["DateOfIssue"] = dtpIssueDate.Value.ToShortDateString();
                dr["PassportExpirDate"] = dtpExpirDate.Value.ToShortDateString();
                dr["Insurance"] = (chkIns.Checked ? true : false);
                dr["TradeUnion"] = (chkTU.Checked ? true : false);
                dr["Basic_Salary"] = nudBasicSal.Value;
                dr["CompAllowance"] = nudAllowance.Value;
                dr["Probation"] = cboProbation.SelectedIndex;
                dr["Basic_Salary"] = nudBasicSal.Value;
                dr["CompAllowance"] = nudAllowance.Value;
            }

            string ls_ColName = "", ls_TableName = "";
            string ls_Error = mCtrlGeneral.Update(mdaPFGUpdate, mdsPersonalGeneral, "HRM_PersonalProfile", out ls_ColName, out ls_TableName);
            if (ls_Error == "")
            {
                mdsPersonalGeneral.AcceptChanges();
                if (!SaveTabPage()) return;
                if (GetCurrentAction() == MODES.ADD)
                {
                    LoadData();
                    if (mRowManager.Count > 0)
                        mRowManager.Position = GetLastIDPosition(lsLastID);
                    PGSetValue();
                    tabProfile_SelectedIndexChanged(null, null);                
                }
                base.save();
                SetReadOnly(this, false);
            }
            else
                MessageBox.Show("Cannot update Personal Profile'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            this.ResumeLayout(true);
        }

        #endregion

        #region cancel
        public override void cancel()
        {
            if (mdsPersonalGeneral == null) return;
            mRowManager.EndCurrentEdit();
            mdsPersonalGeneral.RejectChanges();

            base.cancel();
            if (mRowManager != null && mRowManager.Count > 0) PGSetValue();
            else ResetValue(this);
            tabProfile_SelectedIndexChanged(((TabPage)tab_Profile.SelectedTab), null);
            SetReadOnly(this, false);
            //SetEnableButton(this, true);
        }
        #endregion

        #region Override delete
        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = mdsPersonalGeneral;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            int li_Pos = mRowManager.Position;
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaPFGUpdate, ldsDelete, "HRM_PersonalProfile", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                mRowManager.Position = li_Pos;
                SetReadOnly(this, false);
                return;
            }
            else
                DeleteTabPage();	//Delete TabPage
            base.post_delete();
            if (mRowManager != null && mRowManager.Count > 0) PGSetValue();
            else ResetValue(this);
            SetReadOnly(this, false);
        }
        #endregion

        #region Override Move Event
        public override void move_first()
        {
            base.move_first();
            if (mRowManager != null && mRowManager.Count > 0) PGSetValue();
            else ResetValue(this);
            tabProfile_SelectedIndexChanged(null, null);
        }

        public override void move_last()
        {
            base.move_last();
            if (mRowManager != null && mRowManager.Count > 0) PGSetValue();
            else ResetValue(this);
            tabProfile_SelectedIndexChanged(null, null);
        }

        public override void move_next()
        {
            base.move_next();
            if (mRowManager != null && mRowManager.Count > 0) PGSetValue();
            else ResetValue(this);
            tabProfile_SelectedIndexChanged(null, null);
        }

        public override void move_previous()
        {
            base.move_previous();
            if (mRowManager != null && mRowManager.Count > 0) PGSetValue();
            else ResetValue(this);
            tabProfile_SelectedIndexChanged(null, null);
        }
        #endregion

        #region Load Data Tabpages
        private void LoadAllDataTabpages(string as_IDEmp)
        {
            LoadDataProQualify(as_IDEmp);
            LoadDataEducation(as_IDEmp);
            LoadDataHealthBas(as_IDEmp);
            LoadDataRelatives(as_IDEmp);
            LoadDataContract(as_IDEmp);
            LoadDataWrkExper(as_IDEmp);
            LoadDataIntTransfer(as_IDEmp);
            LoadDataFrgLanComputing(as_IDEmp);
        }

        #region Professonal Qualification tabpage
        #region Load data Professonal Qualification
        private void LoadDataProQualify(string as_IDEmp)
        {
            if (mdsProfessQualify != null)
                if (mdsProfessQualify.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsProfessQualify.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        //if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                        if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                            if (ldr["ID_Emp"].ToString().Equals("")) 
                                return;
                            else if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;

                    }
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'" + " Order By Begin_Date ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select ID_Emp, ID_Qualify, NameOfInstitution, Begin_Date, End_date, Qualification, "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelQualify "
                    + lCondiction;

                if (mdsProfessQualify != null) mdsProfessQualify.Clear();
                //if (mCurrencyManagerPQ != null) mCurrencyManagerPQ.List.Clear();

                mdsProfessQualify = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelQualify");
                mCtrlGeneral.GetDataWithCondition(out mdaPQUpdate, "HRM_PersonnelQualify", lCondiction1);

                if (mdsProfessQualify == null) return;

                mdbg_ProfQualify.DataSource = mdsProfessQualify;
                mdbg_ProfQualify.DataMember = "HRM_PersonnelQualify";

                mCurrencyManagerPQ = (CurrencyManager)mdbg_ProfQualify.BindingContext[mdsProfessQualify, "HRM_PersonnelQualify"];
                mCurrencyManagerPQ.PositionChanged += new EventHandler(RowMaster_Changed);
                mCurrencyManagerPQ.ResumeBinding();

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD) mdbg_ProfQualify.AllowUserToAddRows = false;

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Professonal Qualification'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SavePQ()
        {
            try
            {
                if (mdsProfessQualify == null || txtIDEmp.Text.Trim().Equals(""))
                {
                    mdbg_ProfQualify.AllowUserToAddRows = false;
                    return true;
                }
                mdsProfessQualify = (DataSet)mdbg_ProfQualify.DataSource;
                if (mdsProfessQualify.Tables[0].Rows.Count == 0)
                {
                    mdbg_ProfQualify.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsProfessQualify.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["NameOfInstitution"].ToString().Equals("") && ldr["Qualification"].ToString().Equals(""))
                        {
                            mdbg_ProfQualify.AllowUserToAddRows = false;
                            return true;
                        }
                        if (!ldr["ID_Emp"].ToString().Equals("") && ldr["ID_Emp"].ToString() != txtIDEmp.Text.Trim())
                        {
                            mdbg_ProfQualify.AllowUserToAddRows = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_ProfQualify.AllowUserToAddRows = false;
                    }
                }

                mdbg_ProfQualify.AllowUserToAddRows = false;
                mCurrencyManagerPQ.EndCurrentEdit();

                if (!mdsProfessQualify.HasChanges())
                {
                    mdbg_ProfQualify.AllowUserToAddRows = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsProfessQualify.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    else if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Emp"] = txtIDEmp.Text.Trim();
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaPQUpdate, ldsHasChanged, "HRM_PersonnelQualify", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsProfessQualify.AcceptChanges();
                    //if(GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                    LoadDataProQualify(txtIDEmp.Text.Trim());
                    mdbg_ProfQualify.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save/ update 'Professonal Qualification'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region Modify
        private void ModifyPQ()
        { AddPQ(); }
        #endregion

        #region Add
        private void AddPQ()
        {
            mdbg_ProfQualify.Focus();
            mdbg_ProfQualify.AllowUserToAddRows = true;
            mCurrencyManagerPQ.Position = mdsProfessQualify.Tables[0].Rows.Count;
        }
        #endregion

        #region Cancel
        private void CancelPQ()
        {
            if (mdsProfessQualify != null)
            {
                if (mdsProfessQualify.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerPQ.EndCurrentEdit();
                    mdsProfessQualify.RejectChanges();
                }
                else
                    mdsProfessQualify.Clear();
            }
            //mdbg_ProfQualify.AllowUserToAddRows = true;
        }
        #endregion

        #region Delete
        private void DeletePQ()
        {
            if (mdsProfessQualify == null) return;
            if (mdsProfessQualify.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = (DataSet)mdbg_ProfQualify.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaPQUpdate, ldsDelete, "HRM_PersonnelQualify", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Professonal Qualification'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion

        #region Education tabpage
        #region Load data Education
        private void LoadDataEducation(string as_IDEmp)
        {
            if (mdsEducation != null)
                if (mdsEducation.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsEducation.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'" + " Order By Begin_Date ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select ID_Emp, ID_Education, SchoolOrInsti, Major, Qualification, Levels, Training_Form, Begin_Date, End_date, Note, "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelEducation "
                    + lCondiction;

                mdsEducation = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelEducation");
                mCtrlGeneral.GetDataWithCondition(out mdaEducationUpdate, "HRM_PersonnelEducation", lCondiction1);

                if (mdsEducation == null) return;

                mdbg_Education.DataSource = mdsEducation;
                mdbg_Education.DataMember = "HRM_PersonnelEducation";

                mCurrencyManagerEducation = (CurrencyManager)mdbg_Education.BindingContext[mdsEducation, "HRM_PersonnelEducation"];
                mCurrencyManagerEducation.PositionChanged += new EventHandler(RowMaster_Changed);

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD) mdbg_Education.AllowUserToAddRows = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Education'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Education: Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SaveEdu()
        {
            try
            {
                if (mdsEducation == null || txtIDEmp.Text.Trim().Equals(""))
                {
                    mdbg_Education.AllowUserToAddRows = false;
                    return true;
                }
                mdsEducation = (DataSet)mdbg_Education.DataSource;
                if (mdsEducation.Tables[0].Rows.Count == 0)
                {
                    mdbg_Education.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsEducation.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["SchoolOrInsti"].ToString().Equals("") && ldr["Major"].ToString().Equals("") && ldr["Qualification"].ToString().Equals("")
                            && ldr["Levels"].ToString().Equals("") && ldr["Training_Form"].ToString().Equals("") && ldr["Note"].ToString().Equals(""))
                        {
                            mdbg_Education.AllowUserToAddRows = false;
                            return true;
                        }
                        if (!ldr["ID_Emp"].ToString().Equals("") && ldr["ID_Emp"].ToString() != txtIDEmp.Text.Trim())
                        {
                            mdbg_Education.AllowUserToAddRows = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_Education.AllowUserToAddRows = false;
                    }
                }

                mdbg_Education.AllowUserToAddRows = false;
                mCurrencyManagerEducation.EndCurrentEdit();

                if (!mdsEducation.HasChanges())
                {
                    mdbg_Education.AllowUserToAddRows = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsEducation.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    else if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Emp"] = txtIDEmp.Text;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaEducationUpdate, ldsHasChanged, "HRM_PersonnelEducation", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsEducation.AcceptChanges();
                    //if(GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                    LoadDataEducation(txtIDEmp.Text.Trim());
                    mdbg_Education.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save/ update 'Education'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region Modify
        private void ModifyEdu()
        { AddEdu(); }
        #endregion

        #region Add
        private void AddEdu()
        {
            mdbg_Education.Focus();
            mdbg_Education.AllowUserToAddRows = true;
            mCurrencyManagerEducation.Position = mdsEducation.Tables[0].Rows.Count-1;
        }
        #endregion

        #region Cancel
        private void CancelEdu()
        {
            if (mdsEducation != null)
            {
                if (mdsEducation.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerEducation.EndCurrentEdit();
                    mdsEducation.RejectChanges();
                }
                else
                    mdsEducation.Clear();
            }
            mdbg_Education.AllowUserToAddRows = true;
        }
        #endregion

        #region Delete
        private void DeleteEdu()
        {
            if (mdsEducation == null) return;
            if (mdsEducation.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = (DataSet)mdbg_Education.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaEducationUpdate, ldsDelete, "HRM_PersonnelEducation", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Education'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion

        #region Health tabpage
        #region Load data Health
        private void LoadDataHealthBas(string as_IDEmp)
        {
            if (mdsHealthBas != null)
                if (mdsHealthBas.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsHealthBas.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select ID_Emp, ID_HealthCheck, Height, Weight, Blood, Health_Status, "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelHelthCheckBas "
                    + lCondiction;

                mdsHealthBas = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelHelthCheckBas");
                mCtrlGeneral.GetDataWithCondition(out mdaHealthBasUpdate, "HRM_PersonnelHelthCheckBas", lCondiction1);

                if (mdsHealthBas == null) return;

                ClearDataBinding(tpg_Health);

                txtHealth_IDEmp.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "ID_Emp"));
                //nudHeight.DataBindings.Add(new Binding("Value", mdsHealthBas.Tables[0], "Height"));
                //nudWeight.DataBindings.Add(new Binding("Value", mdsHealthBas.Tables[0], "Weight"));
                txtBlood.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "Blood"));
                txtHealthStatus.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "Health_Status"));

                mCurrencyManagerHealthBas = (CurrencyManager)txtHealth_IDEmp.BindingContext[mdsHealthBas.Tables[0]];
                mCurrencyManagerHealthBas.PositionChanged += new EventHandler(RowDetail_Changed);

                if (GetCurrentAction() == MODES.ADD)
                { AddHealth(); }
                else if (GetCurrentAction() == MODES.MODIFY)
                { 
                    ModifyHealth();
                    SetNumericValueHealth();
                }
                else
                {
                    SetNumericValueHealth();
                }
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Health'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        private void SetNumericValueHealth()
        {
            if (mCurrencyManagerHealthBas == null || mCurrencyManagerHealthBas.Position == -1) return;
            if (mdsHealthBas == null || mdsHealthBas.Tables == null || mdsHealthBas.Tables[0].Rows.Count <= 0) return;
            nudHeight.Value = decimal.Parse(mdsHealthBas.Tables[0].Rows[mCurrencyManagerHealthBas.Position]["Height"].ToString());
            nudWeight.Value = decimal.Parse(mdsHealthBas.Tables[0].Rows[mCurrencyManagerHealthBas.Position]["Weight"].ToString());
        }

        #region Education: Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SaveHealth()
        {
            if (mCurrencyManagerHealthBas == null) return true;
            mCurrencyManagerHealthBas.EndCurrentEdit();
            if (!mdsHealthBas.HasChanges()) return true;

            DataRow dr = mdsHealthBas.Tables[0].Rows[0];
            
            if (dr.RowState == DataRowState.Modified)
            {
                dr["Height"] = nudHeight.Value;
                dr["Weight"] = nudWeight.Value;
                dr["UpdatedUser"] = mMainForm.ms_UserID;
                dr["UpdatedDate"] = DateTime.Now;
            }
            else if (dr.RowState == DataRowState.Added)
            {
                dr["Height"] = nudHeight.Value;
                dr["Weight"] = nudWeight.Value;
                dr["ID_Emp"] = txtIDEmp.Text.Trim();
                dr["CreatedUser"] = mMainForm.ms_UserID;
                dr["CreatedDate"] = DateTime.Now;
            }

            string ls_ColName = "", ls_TableName = "";
            string ls_Error = mCtrlGeneral.Update(mdaHealthBasUpdate, mdsHealthBas, "HRM_PersonnelHelthCheckBas", out ls_ColName, out ls_TableName);
            if (ls_Error == "")
            {
                mdsHealthBas.AcceptChanges();
                if (GetCurrentAction() == MODES.ADD) LoadDataHealthBas(txtIDEmp.Text.Trim());
                return true;
            }
            else
                MessageBox.Show("Cannot update Health'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return false;
        }
        #endregion

        #region Modify
        private void ModifyHealth()
        {
            if (mdsHealthBas == null || mdsHealthBas.Tables[0].Rows.Count <= 0) AddHealth();
        }
        #endregion

        #region Add
        private void AddHealth()
        {
            try
            {
                mCurrencyManagerHealthBas.EndCurrentEdit();
                mCurrencyManagerHealthBas.AddNew();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot add new. Error: " + ex.Message, ConstantKeys.Title);
            }
        }
        #endregion

        #region Cancel
        private void CancelHealth()
        {
            if (mdsHealthBas != null)
            {
                if (mdsHealthBas.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerHealthBas.EndCurrentEdit();
                    mdsHealthBas.RejectChanges();
                }
                else
                    mdsHealthBas.Clear();
            }
        }
        #endregion

        #region Delete
        private void DeleteHealth()
        {
            if (mdsHealthBas == null) return;
            if (mdsHealthBas.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = mdsHealthBas;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[0];
            ldrDelete.Delete();

            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaHealthBasUpdate, ldsDelete, "HRM_PersonnelHelthCheckBas", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Health'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion

        #region Relative tabpage
        #region Load data Relatives
        private void LoadDataRelatives(string as_IDEmp)
        {
            if (mdsRelative != null)
                if (mdsRelative.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsRelative.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'" + " Order By YOB desc ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select ID_Emp, ID_Relative, NameOfRelation, Relationship, YOB, Occupation, Wrk_Place, "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelRelative "
                    + lCondiction;

                mdsRelative = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelRelative");
                mCtrlGeneral.GetDataWithCondition(out mdaRelativeUpdate, "HRM_PersonnelRelative", lCondiction1);

                if (mdsRelative == null) return;

                mdbg_Relatives.DataSource = mdsRelative;
                mdbg_Relatives.DataMember = "HRM_PersonnelRelative";

                mCurrencyManagerRelative = (CurrencyManager)mdbg_Relatives.BindingContext[mdsRelative, "HRM_PersonnelRelative"];
                mCurrencyManagerRelative.PositionChanged += new EventHandler(RowMaster_Changed);

                //Caption
                /*mdbg_Relatives.Columns["NameOfRelation"].HeaderText = "Full Name";
                mdbg_Relatives.Columns["NameOfRelation"].Width = 150;
                mdbg_Relatives.Columns["YOB"].HeaderText = "Year Of Birth";
                mdbg_Relatives.Columns["Occupation"].Width = 200;
                mdbg_Relatives.Columns["Wrk_Place"].HeaderText = "Working Place";
                mdbg_Relatives.Columns["Wrk_Place"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                mdbg_Relatives.Columns["ID_Emp"].Visible =
                mdbg_Relatives.Columns["ID_Relative"].Visible =
                mdbg_Relatives.Columns["CreatedUser"].Visible =
                mdbg_Relatives.Columns["CreatedDate"].Visible =
                mdbg_Relatives.Columns["UpdatedUser"].Visible =
                mdbg_Relatives.Columns["UpdatedDate"].Visible = false;*/

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD)
                    mdbg_Relatives.AllowUserToAddRows = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Relatives'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Relative: Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SaveRelative()
        {
            try
            {
                if (mdsRelative == null || txtIDEmp.Text.Trim().Equals(""))
                {
                    mdbg_Relatives.AllowUserToAddRows = false;
                    return true;
                }
                mdsRelative = (DataSet)mdbg_Relatives.DataSource;
                if (mdsRelative.Tables[0].Rows.Count == 0)
                {
                    mdbg_Relatives.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsRelative.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["NameOfRelation"].ToString().Equals("") && ldr["Relationship"].ToString().Equals("")
                            && ldr["YOB"].ToString().Equals("") && ldr["Occupation"].ToString().Equals("") && ldr["Wrk_Place"].ToString().Equals(""))
                        {
                            mdbg_Relatives.AllowUserToAddRows = false;
                            return true;
                        }
                        if (!ldr["ID_Emp"].ToString().Equals("") && ldr["ID_Emp"].ToString() != txtIDEmp.Text.Trim())
                        {
                            mdbg_Relatives.AllowUserToAddRows = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_Relatives.AllowUserToAddRows = false;
                    }
                }

                mdbg_Relatives.AllowUserToAddRows = false;
                mCurrencyManagerRelative.EndCurrentEdit();

                if (!mdsRelative.HasChanges())
                {
                    mdbg_Relatives.AllowUserToAddRows = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsRelative.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    else if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Emp"] = txtIDEmp.Text;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaRelativeUpdate, ldsHasChanged, "HRM_PersonnelRelative", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsRelative.AcceptChanges();
                    LoadDataRelatives(txtIDEmp.Text.Trim());
                    mdbg_Relatives.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save/ update 'Relative'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region Modify
        private void ModifyRelative()
        { AddRelative(); }
        #endregion

        #region Add
        private void AddRelative()
        {
            mdbg_Relatives.Focus();
            mdbg_Relatives.AllowUserToAddRows = true;
            mCurrencyManagerRelative.Position = mdsRelative.Tables[0].Rows.Count;
        }
        #endregion

        #region Cancel
        private void CancelRelative()
        {
            if (mdsRelative != null)
            {
                if (mdsRelative.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerRelative.EndCurrentEdit();
                    mdsRelative.RejectChanges();
                }
                else
                    mdsRelative.Clear();
            }
            mdbg_Relatives.AllowUserToAddRows = true;
        }
        #endregion

        #region Delete
        private void DeleteRelative()
        {
            if (mdsRelative == null) return;
            if (mdsRelative.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = (DataSet)mdbg_Relatives.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaRelativeUpdate, ldsDelete, "HRM_PersonnelRelative", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Relative'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion

        #region Contract tabpage
        #region Load data Contract
        private void LoadDataContract(string as_IDEmp)
        {
            if (mdsContract != null)
                if (mdsContract.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsContract.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where PC.ID_Emp = " + "'" + as_IDEmp + "'" + " Order By PC.Active_Date ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select PC.ID_Emp, PC.ID_Contract, PC.ID_ContractType, CT.ContractType_Name, PC.Contract_No, PC.Active, PC.Sign_date, PC.Active_Date, PC.Deactive_Date,  "
                    + " PC.CreatedUser, PC.UpdatedUser, PC.CreatedDate, PC.UpdatedDate  "
                    + " From HRM_PersonnelContract PC left outer join HRM_ContractType CT on PC.ID_ContractType = CT.ID_ContractType "
                    + lCondiction;

                mdsContract = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelContract");
                mCtrlGeneral.GetDataWithCondition(out mdaContractUpdate, "HRM_PersonnelContract", lCondiction1);

                if (mdsContract == null) return;

                mdbg_Contract.DataSource = mdsContract;
                mdbg_Contract.DataMember = "HRM_PersonnelContract";

                mCurrencyManagerContract = (CurrencyManager)mdbg_Contract.BindingContext[mdsContract, "HRM_PersonnelContract"];
                mCurrencyManagerContract.PositionChanged += new EventHandler(RowMaster_Changed);

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD)
                    mdbg_Contract.AllowUserToAddRows = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Contract'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion
        #region Contract: Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SaveContract()
        {
            try
            {
                if (mdsContract == null || txtIDEmp.Text.Trim().Equals(""))
                {
                    mdbg_Contract.AllowUserToAddRows = false;
                    return true;
                }

                mdsContract = (DataSet)mdbg_Contract.DataSource;
                if (mdsContract.Tables[0].Rows.Count == 0)
                {
                    mdbg_Contract.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsContract.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["ID_ContractType"].ToString().Equals("") && ldr["Contract_No"].ToString().Equals("") && ldr["Active"].ToString().Equals("")
                            && ldr["Sign_date"].ToString().Equals("") && ldr["Active_Date"].ToString().Equals("") && ldr["Deactive_Date"].ToString().Equals(""))
                        {
                            mdbg_Contract.AllowUserToAddRows = false;
                            return true;
                        }
                        if (!ldr["ID_Emp"].ToString().Equals("") && ldr["ID_Emp"].ToString() != txtIDEmp.Text.Trim())
                        {
                            mdbg_Contract.AllowUserToAddRows = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_Contract.AllowUserToAddRows = false;
                    }
                }

                mdbg_Contract.AllowUserToAddRows = false;
                mCurrencyManagerContract.EndCurrentEdit();

                if (!mdsContract.HasChanges())
                {
                    mdbg_Contract.AllowUserToAddRows = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsContract.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    else if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Emp"] = txtIDEmp.Text.Trim();
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaContractUpdate, ldsHasChanged, "HRM_PersonnelContract", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsContract.AcceptChanges();
                    LoadDataContract(txtIDEmp.Text.Trim());
                    mdbg_Contract.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save/ update 'Contract'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion
        #region Modify
        private void ModifyContract()
        { AddContract(); }
        #endregion
        #region Add
        private void AddContract()
        {
            mdbg_Contract.Focus();
            mdbg_Contract.AllowUserToAddRows = true;
            mCurrencyManagerContract.Position = mdsContract.Tables[0].Rows.Count - 1;
        }
        #endregion
        #region Cancel
        private void CancelContract()
        {
            if (mdsContract != null)
            {
                if (mdsContract.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerContract.EndCurrentEdit();
                    mdsContract.RejectChanges();
                }
                else
                    mdsContract.Clear();
            }
            mdbg_Contract.AllowUserToAddRows = true;
        }
        #endregion
        #region Delete
        private void DeleteContract()
        {
            if (mdsContract == null) return;
            if (mdsContract.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = (DataSet)mdbg_Contract.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaContractUpdate, ldsDelete, "HRM_PersonnelContract", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Contract'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion

        #region Working Experience tabpage
        #region Load data Working Experience
        private void LoadDataWrkExper(string as_IDEmp)
        {
            if (mdsWrkExperience != null)
                if (mdsWrkExperience.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsWrkExperience.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'" + " Order By Begin_Date ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select ID_Emp, ID_WrkExper, Begin_Date, End_Date, POW, Position, Respons, Sal_Starting, Sal_LastDrawn, Leave_Reason, "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelWrkExper "
                    + lCondiction;

                mdsWrkExperience = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelWrkExper");
                mCtrlGeneral.GetDataWithCondition(out mdaWrkExperienceUpdate, "HRM_PersonnelWrkExper", lCondiction1);

                if (mdsWrkExperience == null) return;

                mdbg_WrkExpirence.DataSource = mdsWrkExperience;
                mdbg_WrkExpirence.DataMember = "HRM_PersonnelWrkExper";

                mCurrencyManagerWrkExperience = (CurrencyManager)mdbg_WrkExpirence.BindingContext[mdsWrkExperience, "HRM_PersonnelWrkExper"];
                mCurrencyManagerWrkExperience.PositionChanged += new EventHandler(RowMaster_Changed);

                //Caption
                /*mdbg_WrkExpirence.Columns["Begin_Date"].HeaderText = "Start Date";
                mdbg_WrkExpirence.Columns["End_Date"].HeaderText = "End Date";
                mdbg_WrkExpirence.Columns["POW"].HeaderText = "Place Of Work";
                mdbg_WrkExpirence.Columns["POW"].Width = 250;
                mdbg_WrkExpirence.Columns["Position"].HeaderText = "Position Held";
                mdbg_WrkExpirence.Columns["Respons"].HeaderText = "Responsibilities";
                mdbg_WrkExpirence.Columns["Sal_Starting"].HeaderText = "Salary Starting";
                mdbg_WrkExpirence.Columns["Sal_Starting"].DefaultCellStyle.Format = "###,###,###,###,###,##0";
                mdbg_WrkExpirence.Columns["Sal_LastDrawn"].HeaderText = "Salary Last Drawn";
                mdbg_WrkExpirence.Columns["Sal_LastDrawn"].DefaultCellStyle.Format = "###,###,###,###,###,##0";
                mdbg_WrkExpirence.Columns["Leave_Reason"].HeaderText = "Leave Reason";
                mdbg_WrkExpirence.Columns["Leave_Reason"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                mdbg_WrkExpirence.Columns["ID_Emp"].Visible =
                mdbg_WrkExpirence.Columns["ID_WrkExper"].Visible =
                mdbg_WrkExpirence.Columns["CreatedUser"].Visible =
                mdbg_WrkExpirence.Columns["CreatedDate"].Visible =
                mdbg_WrkExpirence.Columns["UpdatedUser"].Visible =
                mdbg_WrkExpirence.Columns["UpdatedDate"].Visible = false;*/

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD)
                    mdbg_WrkExpirence.AllowUserToAddRows = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Working Experience'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion
        #region Working Experience: Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SaveWrkExper()
        {
            try
            {
                if (mdsWrkExperience == null || txtIDEmp.Text.Trim().Equals(""))
                {
                    mdbg_WrkExpirence.AllowUserToAddRows = false;
                    return true;
                }
                mdsWrkExperience = (DataSet)mdbg_WrkExpirence.DataSource;
                if (mdsWrkExperience.Tables[0].Rows.Count == 0)
                {
                    mdbg_WrkExpirence.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsWrkExperience.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["POW"].ToString().Equals("") && ldr["Position"].ToString().Equals("") && ldr["Respons"].ToString().Equals("") 
                            && ldr["Sal_Starting"].ToString().Equals("") && ldr["Sal_LastDrawn"].ToString().Equals("") && ldr["Leave_Reason"].ToString().Equals(""))
                        {
                            mdbg_WrkExpirence.AllowUserToAddRows = false;
                            return true;
                        }
                        if (!ldr["ID_Emp"].ToString().Equals("") && ldr["ID_Emp"].ToString() != txtIDEmp.Text.Trim())
                        {
                            mdbg_WrkExpirence.AllowUserToAddRows = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_WrkExpirence.AllowUserToAddRows = false;
                    }
                }

                mdbg_WrkExpirence.AllowUserToAddRows = false;
                mCurrencyManagerWrkExperience.EndCurrentEdit();

                if (!mdsWrkExperience.HasChanges())
                {
                    mdbg_WrkExpirence.AllowUserToAddRows = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsWrkExperience.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    else if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Emp"] = txtIDEmp.Text;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaWrkExperienceUpdate, ldsHasChanged, "HRM_PersonnelWrkExper", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsWrkExperience.AcceptChanges();
                    LoadDataWrkExper(txtIDEmp.Text.Trim());
                    mdbg_WrkExpirence.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save 'Working Experience'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion
        #region Modify
        private void ModifyWrkExper()
        { AddWrkExper(); }
        #endregion
        #region Add
        private void AddWrkExper()
        {
            mdbg_WrkExpirence.Focus();
            mdbg_WrkExpirence.AllowUserToAddRows = true;
            mCurrencyManagerWrkExperience.Position = mdsWrkExperience.Tables[0].Rows.Count;
        }
        #endregion
        #region Cancel
        private void CancelWrkExper()
        {
            if (mdsWrkExperience != null)
            {
                if (mdsWrkExperience.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerWrkExperience.EndCurrentEdit();
                    mdsWrkExperience.RejectChanges();
                }
                else
                    mdsWrkExperience.Clear();
            }
            mdbg_WrkExpirence.AllowUserToAddRows = true;
        }
        #endregion
        #region Delete
        private void DeleteWrkExper()
        {
            if (mdsWrkExperience == null) return;
            if (mdsWrkExperience.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = (DataSet)mdbg_WrkExpirence.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaWrkExperienceUpdate, ldsDelete, "HRM_PersonnelWrkExper", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Working Experience'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion

        #region Internal Transfer tabpage
        #region Load data Internal Transfer
        private void LoadDataIntTransfer(string as_IDEmp)
        {
            if (mdsIntTransfer != null)
                if (mdsIntTransfer.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsIntTransfer.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'" + " Order By Begin_Date ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select  "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelWrkExper "
                    + lCondiction;

                mdsIntTransfer = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelWrkExper");
                mCtrlGeneral.GetDataWithCondition(out mdaWrkExperienceUpdate, "HRM_PersonnelWrkExper", lCondiction1);

                if (mdsIntTransfer == null) return;

                mdbg_InternalTransfer.DataSource = mdsIntTransfer;
                mdbg_InternalTransfer.DataMember = "HRM_PersonnelWrkExper";

                mCurrencyManagerIntTransfer = (CurrencyManager)mdbg_WrkExpirence.BindingContext[mdsIntTransfer, "HRM_PersonnelWrkExper"];
                mCurrencyManagerIntTransfer.PositionChanged += new EventHandler(RowMaster_Changed);

                //Caption
                mdbg_InternalTransfer.Columns["Begin_Date"].HeaderText = "Start Date";
                mdbg_InternalTransfer.Columns["End_Date"].HeaderText = "End Date";
                mdbg_InternalTransfer.Columns["POW"].HeaderText = "Place Of Work";
                mdbg_InternalTransfer.Columns["POW"].Width = 250;
                mdbg_InternalTransfer.Columns["Position"].HeaderText = "Position Held";
                mdbg_InternalTransfer.Columns["Respons"].HeaderText = "Responsibilities";
                mdbg_InternalTransfer.Columns["Sal_Starting"].HeaderText = "Salary Starting";
                mdbg_InternalTransfer.Columns["Sal_Starting"].DefaultCellStyle.Format = "###,###,###,###,###,##0";
                mdbg_InternalTransfer.Columns["Sal_LastDrawn"].HeaderText = "Salary Last Drawn";
                mdbg_InternalTransfer.Columns["Sal_LastDrawn"].DefaultCellStyle.Format = "###,###,###,###,###,##0";
                mdbg_InternalTransfer.Columns["Leave_Reason"].HeaderText = "Leave Reason";
                mdbg_InternalTransfer.Columns["Leave_Reason"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                mdbg_InternalTransfer.Columns["ID_Emp"].Visible =
                mdbg_InternalTransfer.Columns["CreatedUser"].Visible =
                mdbg_InternalTransfer.Columns["CreatedDate"].Visible =
                mdbg_InternalTransfer.Columns["UpdatedUser"].Visible =
                mdbg_InternalTransfer.Columns["UpdatedDate"].Visible = false;

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD)
                    mdbg_InternalTransfer.AllowUserToAddRows = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Internal Transfer'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion
        #endregion

        #region Foreign Language tabpage
        #region Load data Foreign Language Computing
        private void LoadDataFrgLanComputing(string as_IDEmp)
        {
            if (mdsFLanComputing != null)
                if (mdsFLanComputing.Tables[0].Rows.Count > 0)
                {
                    DataRow ldr = mdsFLanComputing.Tables[0].Rows[0];
                    if (ldr["ID_Emp"].ToString() == txtIDEmp.Text.Trim()) return;
                    if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                        if (ldr["ID_Emp"].ToString().Equals("")) return;
                }
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where ID_Emp = " + "'" + as_IDEmp + "'" + " Order By Skill_Name ";
                string lCondiction1 = " ID_Emp = " + "'" + as_IDEmp + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select ID_Emp, ID_LanSkill, Skill_Name, Level_Skill, Note, "
                    + " CreatedUser, UpdatedUser, CreatedDate, UpdatedDate  "
                    + " From HRM_PersonnelLanSkill "
                    + lCondiction;

                mdsFLanComputing = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelLanSkill");
                mCtrlGeneral.GetDataWithCondition(out mdaFLanComputingUpdate, "HRM_PersonnelLanSkill", lCondiction1);

                if (mdsFLanComputing == null) return;

                mdbg_LanComputing.DataSource = mdsFLanComputing;
                mdbg_LanComputing.DataMember = "HRM_PersonnelLanSkill";

                mCurrencyManagerFLanComputing = (CurrencyManager)mdbg_LanComputing.BindingContext[mdsFLanComputing, "HRM_PersonnelLanSkill"];
                mCurrencyManagerFLanComputing.PositionChanged += new EventHandler(RowMaster_Changed);

                //Caption
                /*mdbg_LanComputing.Columns["Skill_Name"].HeaderText = "Skill/Literacy Name";

                mdbg_LanComputing.Columns["Level_Skill"].HeaderText = "Level";
                mdbg_LanComputing.Columns["Note"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

                mdbg_LanComputing.Columns["ID_Emp"].Visible =
                mdbg_LanComputing.Columns["ID_LanSkill"].Visible =
                mdbg_LanComputing.Columns["CreatedUser"].Visible =
                mdbg_LanComputing.Columns["CreatedDate"].Visible =
                mdbg_LanComputing.Columns["UpdatedUser"].Visible =
                mdbg_LanComputing.Columns["UpdatedDate"].Visible = false;*/

                if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD)
                    mdbg_LanComputing.AllowUserToAddRows = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load data: 'Foreign Language and Computing'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion
        #region Foreign Language & Computing: Save, Modify, Add, Cancel, Delete
        #region Save
        private bool SaveFrgLanComp()
        {
            try
            {
                if (mdsFLanComputing == null || txtIDEmp.Text.Trim().Equals(""))
                {
                    mdbg_LanComputing.AllowUserToAddRows = false;
                    return true;
                }
                mdsFLanComputing = (DataSet)mdbg_LanComputing.DataSource;
                if (mdsFLanComputing.Tables[0].Rows.Count == 0)
                {
                    mdbg_LanComputing.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsFLanComputing.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["Skill_Name"].ToString().Equals("") && ldr["Level_Skill"].ToString().Equals("") && ldr["Note"].ToString().Equals(""))
                        {
                            mdbg_LanComputing.AllowUserToAddRows = false;
                            return true;
                        }
                        if (!ldr["ID_Emp"].ToString().Equals("") && ldr["ID_Emp"].ToString() != txtIDEmp.Text.Trim())
                        {
                            mdbg_LanComputing.AllowUserToAddRows = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_LanComputing.AllowUserToAddRows = false;
                    }
                }

                mdbg_LanComputing.AllowUserToAddRows = false;
                mCurrencyManagerFLanComputing.EndCurrentEdit();

                if (!mdsFLanComputing.HasChanges())
                {
                    mdbg_LanComputing.AllowUserToAddRows = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsFLanComputing.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    else if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Emp"] = txtIDEmp.Text;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaFLanComputingUpdate, ldsHasChanged, "HRM_PersonnelLanSkill", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsFLanComputing.AcceptChanges();
                    LoadDataFrgLanComputing(txtIDEmp.Text.Trim());
                    mdbg_LanComputing.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save/ update 'Foreign Language/ Computing'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion
        #region Modify
        private void ModifyFrgLanComp()
        { AddFrgLanComp(); }
        #endregion
        #region Add
        private void AddFrgLanComp()
        {
            mdbg_LanComputing.Focus();
            mdbg_LanComputing.AllowUserToAddRows = true;
            mCurrencyManagerFLanComputing.Position = mdsFLanComputing.Tables[0].Rows.Count;
        }
        #endregion
        #region Cancel
        private void CancelFrgLanComp()
        {
            if (mdsFLanComputing != null)
            {
                if (mdsFLanComputing.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerFLanComputing.EndCurrentEdit();
                    mdsFLanComputing.RejectChanges();
                }
                else
                    mdsFLanComputing.Clear();
            }
            mdbg_LanComputing.AllowUserToAddRows = true;
        }
        #endregion
        #region Delete
        private void DeleteFrgLanComp()
        {
            if (mdsFLanComputing == null) return;
            if (mdsFLanComputing.Tables[0].Rows.Count == 0) return;

            DataSet ldsDelete = (DataSet)mdbg_LanComputing.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaFLanComputingUpdate, ldsDelete, "HRM_PersonnelLanSkill", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("cannot delete Foreign Language/ Computing'. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return;
            }
        }
        #endregion
        #endregion
        #endregion
        #endregion

        #region AddTabPage
        private void AddTabPage()
        {
            if (mdsProfessQualify != null) mdsProfessQualify.Clear();
            if (mdsHealthBas != null) mdsHealthBas.Clear();
            if (mdsEducation != null) mdsEducation.Clear();
            if (mdsRelative != null) mdsRelative.Clear();
            if (mdsContract != null) mdsContract.Clear();
            if (mdsWrkExperience != null) mdsWrkExperience.Clear();
            if (mdsIntTransfer != null) mdsIntTransfer.Clear();
            if (mdsFLanComputing != null) mdsFLanComputing.Clear();

            tab_Profile.SelectedIndex = 0;

            btnCancel.Focus();
        }
        #endregion

        #region SaveTabPage
        private bool SaveTabPage()
        {
            if (!SavePQ()) return false;		//Professonal Qualification
            if (!SaveEdu()) return false;		//Education
            if (!SaveHealth()) return false;    //Health
            if (!SaveRelative()) return false;   //Relative
            if (!SaveContract()) return false;	//Contract
            if (!SaveWrkExper()) return false;  //Working Experience
            //if (!SaveInttrans()) return false;//Internal Transfer
            if (!SaveFrgLanComp()) return false;//Foreign Language
            return true;
        }
        #endregion

        #region DeleteTabPage
        private void DeleteTabPage()
        {
            DeletePQ();             //Professonal Qualification
            DeleteEdu();            //Education
            DeleteHealth();         //Health
            DeleteRelative();	    //Relative
            DeleteContract();	    //Contract
            DeleteWrkExper();	    //Working Experience
            //DeleteIntTransfer();	//Internal Transfer
            DeleteFrgLanComp();	    //Foreign Language/ Computing
            tab_Profile.SelectedIndex = 0;
        }
        #endregion

        #region tabProfile Selected Index Changed
        private void tabProfile_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            switch (tab_Profile.SelectedTab.Name)
            {
                case "tpg_ProfessQualify":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsProfessQualify == null) LoadDataProQualify(txtIDEmp.Text.Trim());
                        AddPQ();
                    }
                    else
                    {
                        LoadDataProQualify(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyPQ();
                    }
                    break;

                case "tpg_Education":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsEducation == null)
                            LoadDataEducation(txtIDEmp.Text.Trim());
                        AddEdu();
                    }
                    else
                    {
                        LoadDataEducation(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyEdu();
                    }
                    break;

                case "tpg_Health":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsHealthBas == null) LoadDataHealthBas(txtIDEmp.Text.Trim());
                        AddHealth();
                    }
                    else
                    {
                        LoadDataHealthBas(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyHealth();
                    }
                    break;

                case "tpg_Relatives":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsRelative == null) LoadDataRelatives(txtIDEmp.Text.Trim());
                        AddRelative();
                    }
                    else
                    {
                        LoadDataRelatives(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyRelative();
                    }
                    break;

                case "tpg_Contract":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsContract == null) LoadDataContract(txtIDEmp.Text.Trim());
                        AddContract();
                    }
                    else
                    {
                        LoadDataContract(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyContract();
                    }
                    break;

                case "tpg_WrkExper":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsWrkExperience == null) LoadDataWrkExper(txtIDEmp.Text.Trim());
                        AddWrkExper();
                    }
                    else
                    {
                        LoadDataWrkExper(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyWrkExper();
                    }
                    break;

                /*case "tpg_IntTransfer":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsIntTransfer == null) LoadDataIntTransfer(txtIDEmp.Text.Trim());
                        AddIntTransfer();
                    }
                    else
                    {
                        LoadDataIntTransfer(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyIntTransfer();
                    }
                    break;*/

                case "tpg_FrgLanComp":
                    if (GetCurrentAction() == MODES.ADD)
                    {
                        if (mdsFLanComputing == null) LoadDataFrgLanComputing(txtIDEmp.Text.Trim());
                        AddFrgLanComp();
                    }
                    else
                    {
                        LoadDataFrgLanComputing(txtIDEmp.Text.Trim());
                        if (GetCurrentAction() == MODES.MODIFY) ModifyFrgLanComp();
                    }
                    break;
            }
        }
        #endregion

        #region Save & Cancel Buttons Event
        private void btnok_Click(object sender, System.EventArgs e) { save(); }
        private void btncancel_Click(object sender, System.EventArgs e) { cancel(); }
        #endregion

        public override void btn_Click(object sender, EventArgs e)
        {
            if (GetCurrentAction() == MODES.FULL || GetCurrentAction() == MODES.VOID) return;
            switch (((Button)sender).Name)
            { 
                case "btnIDPosition":
                    OpenSelection("txtIDPosition");
                    break;

                case "btnIDDept":
                    OpenSelection("txtIDDept");
                    break;

                case "btnIDResideState":
                    OpenSelection("txtIDResideState");
                    break;

                case "btnIDResideCountry":
                    OpenSelection("txtIDResideCountry");
                    break;

                case "btnIDContState":
                    OpenSelection("txtIDContState");
                    break;

                case "btnIDContCountry":
                    OpenSelection("txtIDContCountry");
                    break;

                case "btnIDNative":
                    OpenSelection("txtIDNative");
                    break;

                case "btnIDNationality":
                    OpenSelection("txtIDNationality");
                    break;

                case "btnIDRace":
                    OpenSelection("txtIDRace");
                    break;

                case "btnIDLiteracy":
                    OpenSelection("txtIDLiteracy");
                    break;

                case "btnIDBank":
                    OpenSelection("txtIDBank");
                    break;

                case "btnIDGLAccGroup":
                    OpenSelection("txtIDGLAccGroup");
                    break;
            }
        }

        public override void OpenSelection(string as_SelectioField)
        {
            SelectionParam lstr_param = new SelectionParam();
            lstr_param.ms_SelectionField = as_SelectioField;
            FormSelection lfrmSelect = new FormSelection();
            lfrmSelect.mfrmParentForm = this;
            lfrmSelect.Owner = mMainForm;

            switch (as_SelectioField)
            {
                case "txtIDPosition":
						lstr_param.ms_SelectionName = "Position";
						lfrmSelect.SetParam(lstr_param);
						if(lfrmSelect.ShowDialog() == DialogResult.OK) 
						{
							txtIDPosition.Focus();
                            txtIDPosition.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
							lblPositionName.Focus();
                            lblPositionName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
							this.SelectNextControl(this.ActiveControl, true, true, true, true);
						} break;

                case "txtIDDept":
                    lstr_param.ms_SelectionName = "Department";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDDept.Focus();
                        txtIDDept.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblDeptName.Focus();
                        lblDeptName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDResideState":
                    lstr_param.ms_SelectionName = "State";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDResideState.Focus();
                        txtIDResideState.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblResideStateName.Focus();
                        lblResideStateName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDResideCountry":
                    lstr_param.ms_SelectionName = "Country";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDResideCountry.Focus();
                        txtIDResideCountry.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblResideCountryName.Focus();
                        lblResideCountryName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDContState":
                    lstr_param.ms_SelectionName = "State";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDContState.Focus();
                        txtIDContState.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblContStateName.Focus();
                        lblContStateName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDContCountry":
                    lstr_param.ms_SelectionName = "Country";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDContCountry.Focus();
                        txtIDContCountry.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblContCountryName.Focus();
                        lblContCountryName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                    

                case "txtIDNative":
                    lstr_param.ms_SelectionName = "Native";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDNative.Focus();
                        txtIDNative.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblNativeName.Focus();
                        lblNativeName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDNationality":
                    lstr_param.ms_SelectionName = "Nationality";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDNationality.Focus();
                        txtIDNationality.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblNationalityName.Focus();
                        lblNationalityName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDRace":
                    lstr_param.ms_SelectionName = "Race/Dialect";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDRace.Focus();
                        txtIDRace.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblRaceName.Focus();
                        lblRaceName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDLiteracy":
                    lstr_param.ms_SelectionName = "Literacy";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDLiteracy.Focus();
                        txtIDLiteracy.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblLiteracyName.Focus();
                        lblLiteracyName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDBank":
                    lstr_param.ms_SelectionName = "Bank";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDBank.Focus();
                        txtIDBank.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblBankName.Focus();
                        lblBankName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "txtIDGLAccGroup":
                    lstr_param.ms_SelectionName = "GL Account Group";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        txtIDGLAccGroup.Focus();
                        txtIDGLAccGroup.Text = lfrmSelect.GetParam().msa_ReturnValues[0].ToString();
                        lblGLAccGrpName.Focus();
                        lblGLAccGrpName.Text = lfrmSelect.GetParam().msa_ReturnValues[1].ToString();
                        this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;

                case "ID_ContractTypeCont":
                    lstr_param.ms_SelectionName = "Contract Type";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        mdbg_Contract["ID_ContractTypeCont", mdbg_Contract.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[0];
                        mdbg_Contract["ContractType_NameCont", mdbg_Contract.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[1];
                        //this.SelectNextControl(this.ActiveControl, true, true, true, true);
                    } break;
            
            }
        }

        private void nudHeight_ValueChanged(object sender, EventArgs e)
        {
            if (mdsHealthBas == null || mdsHealthBas.Tables[0].Rows.Count <= 0
                || mCurrencyManagerHealthBas == null || mCurrencyManagerHealthBas.Position == -1) return;
            if(GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                mdsHealthBas.Tables[0].Rows[mCurrencyManagerHealthBas.Position]["Height"] = nudHeight.Value;
        }

        private void nudWeight_ValueChanged(object sender, EventArgs e)
        {
            if (mdsHealthBas == null || mdsHealthBas.Tables[0].Rows.Count <= 0
                || mCurrencyManagerHealthBas == null || mCurrencyManagerHealthBas.Position == -1) return;
            if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
                mdsHealthBas.Tables[0].Rows[mCurrencyManagerHealthBas.Position]["Weight"] = nudWeight.Value;
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (GetCurrentAction() == MODES.ADD || GetCurrentAction() == MODES.MODIFY)
            {
                //txtFullName.Text = txtFirstName.Text.Trim() + " " + txtMiddleName.Text.Trim() +" " + txtLastName.Text.Trim();
            }
        }

        private void mdbg_Contract_KeyUp(object sender, KeyEventArgs e)
        {
            if (GetCurrentAction() == MODES.FULL || GetCurrentAction() == MODES.VOID) return;
            if (e.KeyCode != Keys.F9) return;
            OpenSelection(mdbg_Contract.Columns[mdbg_Contract.CurrentCell.ColumnIndex].Name);
        }

        private void mdbg_Contract_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            //e.Cancel = true;
        }

        private void pbxEmployee_MouseHover(object sender, EventArgs e)
        {
            if (GetCurrentAction() == MODES.MODIFY || GetCurrentAction() == MODES.ADD) Cursor = Cursors.Hand;
        }

        private void pbxEmployee_MouseLeave(object sender, EventArgs e)
        {
            if (GetCurrentAction() == MODES.MODIFY || GetCurrentAction() == MODES.ADD) Cursor = Cursors.Default;
        }

        private void pbxEmployee_MouseUp(object sender, MouseEventArgs e)
        {
            if (GetCurrentAction() != MODES.MODIFY && GetCurrentAction() != MODES.ADD) return;
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (pbxEmployee.Image != null)
                    if (MessageBox.Show("Are you sure change employee's picture?", ConstantKeys.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) return;

                OpenFileDialog lOFD = new OpenFileDialog();
                lOFD.Filter = "Image files (*.bmp)|*.bmp|All Files (*.*)|*.*";
                lOFD.RestoreDirectory = true;

                if (lOFD.ShowDialog() == DialogResult.OK)
                {
                    pbxEmployee.Image = mCtrlGeneral.SetImage(lOFD.FileName.Trim());
                    mdsPersonalGeneral.Tables[0].Rows[mRowManager.Position]["Emp_Picture"] = mCtrlGeneral.CImg2Byte(pbxEmployee.Image);
                }
            }
            else if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (MessageBox.Show("Are you sure delete employee's picture?", ConstantKeys.Title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) return;
                pbxEmployee.Image = null;
                mdsPersonalGeneral.Tables[0].Rows[mRowManager.Position]["Emp_Picture"] = DBNull.Value;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
        }

        public override void SetListChanged()
        {
            PGSetValue();
            tabProfile_SelectedIndexChanged(null, null);
        }

        protected override void DeleteRowGrid()
        {
            try
            {
                CustomDataGrdView lDGV = (CustomDataGrdView)this.GetFocusedControl();
                if (lDGV == null || lDGV.CurrentCell == null) return;
                int icurrRow = lDGV.CurrentCell.RowIndex;
                DataSet ldsDelete = (DataSet)lDGV.DataSource;
                ldsDelete.Tables[0].Rows[icurrRow].Delete();
            }
            catch (Exception ex)
            {
                Ctrl_LOG.Print("In PersonalProfile Form", "At DeleteRowGrid method", "Error message: " + ex.Message);
            }
        }
    }
}
